package cn.sharetraffic.mi.etongdai;

import cn.sharetraffic.mi.FindListener;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 功能：易通贷顾客<br>
 * 作者：蒋睿立<br>
 * 时间：2017年7月18日<br>
 * 版本：1.1<br>
 * 有货才log.info否则都log.debug
 */
public abstract class BaseETDCustomer {
    public long nowTime;//当前时间
    private Logger log = Logger.getLogger(getClass());
    private FindListener onFindListener;
    private long nextHttpTime;//访问http的时间


    public BaseETDCustomer(){
        this.setOnFindListener(new FindListener() {
            final int 初始间隔 = 60;
            private int delayTime = 初始间隔;
            private int second;//临时延时时间

            @Override
            public void setDelayTime(int time) {
                if(time <= 0) {
                    this.delayTime = 0x1ffffff;
                }else {
                    this.delayTime = time;
                }
                log.info("新间隔[" + this.delayTime + "秒]访问");
                exactlyOnTime();
            }

            @Override
            public int getDelayTime() {
                return delayTime;
            }

            @Override
            public void exactlyOnTime() {
                log.info("[" + delayTime + "秒]后访问");
                nextHttpTime = System.currentTimeMillis() + delayTime*1000L;
            }

            @Override
            public void timeout() {
                second += 初始间隔;
                log.info("延时["+(delayTime+second)+"秒]访问");
                nextHttpTime = System.currentTimeMillis() + (delayTime+second)*1000L;
            }
        });
    }

    public List<DebtEntity> packageEntity(Map<String, String> data){
        List<DebtEntity> list = new ArrayList<>();
        Document doc = findGoods(data);
        if(doc == null){
            //可能java.net.SocketTimeoutException: connect timed out
            return null;
        }
        Element body = doc.body();
        Element funds = body.getElementById("funds");
        Elements funds_list = funds.getElementsByClass("funds-list");
        for (int i = 0; i < funds_list.size(); i++) {
            //项目
            Element fund = funds_list.get(i);
            DebtEntity entity = parseEntity(fund);
            list.add(entity);
        }
        return list;
    }

    private DebtEntity parseEntity(Element fund) {
        DebtEntity entity = new DebtEntity();
        //时间
        Elements termClass = fund.getElementsByClass("term");
        String term = termClass.first().child(0).ownText();
        for (DebtEntity.Repay r: DebtEntity.Repay.values()) {
            if (r.date.equals(term)){
                entity.setRepay(r);
                break;
            }
        }
        //预期收益率
        Elements rateClass = fund.getElementsByClass("rate");
        String rate = rateClass.first().child(0).ownText();
        if(rate.indexOf("%") == -1){
            entity.setRate(rate);
        }
        else {
            entity.setRate(rate.substring(0, rate.length()-1));
        }
        //募集进度
        Elements progressClass = fund.getElementsByClass("progress");
        String progress = progressClass.first().child(1).text();
        if(progress.indexOf("%") == -1){
            entity.setProgress(progress);
        }
        else {
            entity.setProgress(progress.substring(0, progress.length()-1));
        }
        //还款方式
        Elements repayTypeClass = fund.getElementsByClass("mode");
        String repayType = repayTypeClass.first().child(1).text();
        repayType = repayType.substring(0, repayType.length() - 4);
        DebtEntity.RepayType type = DebtEntity.RepayType.valueOf(repayType);
        entity.setRepayType(type);
        return entity;
    }

    protected Document findGoods(Map<String, String> data) {
        //检查可否访问
        nowTime = System.currentTimeMillis();
        if(nowTime < nextHttpTime){
            return null;
        }

        String url = "http://app.etongdai.com/investments/index";
        log.debug(url);
        Document reValue = null;
        Connection conn = Jsoup.connect(url);
        Connection.Response resp = null;
        try {
            conn.timeout(10000); // 10秒超时
            conn.method(Connection.Method.POST);
            conn.ignoreContentType(true);
            conn.userAgent(
                    "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36");
            conn.referrer("http://www.etongdai.com/");
            conn.data(data);
            resp = conn.execute();
            // 成功获取当前销售状态
            if (resp.statusCode() == 200 && resp.statusMessage().equalsIgnoreCase("ok")) {
                reValue = resp.parse();
            } else {
                log.warn("状态码:" + resp.statusCode() + ",状态值:" + resp.statusMessage());
            }
            if (onFindListener != null) {
                onFindListener.exactlyOnTime();
            }
        } catch (java.io.IOException e) {
            log.error(this.getClass().getName(), e);
            if (onFindListener != null) {
                onFindListener.timeout();
            }
        } catch (JSONException e) {
            if (resp == null) {
                log.error(this.getClass().getName(), e);
            }else {
                log.error(resp.body(), e);
            }
            if (onFindListener != null) {
                onFindListener.timeout();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if (onFindListener != null) {
                onFindListener.timeout();
            }
        }
        return reValue;
    }

    public abstract void shopping();

    public FindListener getOnFindListener() {
        return onFindListener;
    }

    public void setOnFindListener(FindListener onFindListener) {
        this.onFindListener = onFindListener;
    }
}
